require "Common/define"
require "Logic/Config"
require "Common/functions"
---@class ArenaManager
ArenaManager = {};
local this = ArenaManager;

local baseInfo = {}; -- 基础信息
local rankInfo = {}; -- 排行信息
this.resultDic = {};    --埋点信息
--- @type number 排行榜版本号
local rankVersion = -1;
local opponentInfo = {}; --匹配对手信息

--- @type table<number, BattleRecord> 对战记录
local recordInfo = {};
--- @type number 对战记录版本号
local recordVersion = -1;
--- @type table<number, BattleRecord> 精彩战斗记录
local specialBattleInfo = {};

local arenaGradingConfig;
local arenaRewardConfig;
local someBattleSkip = false;--有些战斗不进入战斗直接出结果

function ArenaManager.init()
    this.initBaseInfo();
    this.initCrossBaseInfo()
    this.initCrossTeamBaseInfo()
    arenaRewardConfig = G.dataTable["t_arenareward"];
    arenaGradingConfig = G.dataTable["t_athleticsgrading"];
end

function ArenaManager.initBaseInfo()
    baseInfo["freeTimes"] = HelperFunc.GetGlobalNumVlue(72) -- 每日免费挑战次数
    baseInfo["times"] = 0; --今日已挑战次数
    baseInfo["buyCount"] = 0; -- 今日已购买次数
    baseInfo["endTime"] = 0; -- 本赛季结束时间
    baseInfo["rank"] = 0;  --排行
    baseInfo["score"] = 0;  --积分
    baseInfo["isLevelUp"] = 0;
    baseInfo["seasonEndTime"] = 0; --赛季结束时间(下一次开启)

end

function ArenaManager.setBaseInfo(msg)
    baseInfo["endTime"] = tonumber(tostring(msg["endTime"]));
    baseInfo["seasonEndTime"] = tonumber(tostring(msg["seasonEndTime"]));
    baseInfo["winCount"] = msg["winCount"];
    baseInfo["hasReward"] = msg["drawBox"]; -- 已领取的奖励宝箱
    baseInfo["times"] = msg["battleCount"];
    baseInfo["buyCount"] = msg["buyCount"];
    baseInfo["rank"] = msg["myRank"];  --排行
    baseInfo["score"] = tostring(msg["myScore"]);  --积分
    baseInfo["power"] = msg["myDefPower"];
    baseInfo["isLevelUp"] = 0;

    logicMgr.FormationManager.SetFormation(EnumConst.FormationType.ArenaAtk, msg["ackFormation"]);
    FormationManager.SetFormation(EnumConst.FormationType.ArenaDef, msg["defFormation"]);
end
--- @param msg ResArenaGetRanksMessage msg
function ArenaManager.setRankInfo(msg)
    rankInfo.myRank = rankInfo.myRank or {}
    local roleInfo = logicMgr.HeroManager.GetRoleInfo()
    rankInfo.myRank["playerId"] = roleInfo.playerId;
    rankInfo.myRank["name"] = roleInfo.name;
    rankInfo.myRank["headId"] = roleInfo.pic;
    rankInfo.myRank["level"] = roleInfo.level;
    rankInfo.myRank["power"] = roleInfo.maxPower;
    rankInfo.myRank["headFrame"] = roleInfo.picFrame;

    if rankVersion ~= nil and rankVersion == msg.rankVersion then return end
    rankInfo.myRank["rank"] = msg.myRank;
    rankInfo.myRank["score"] = tonumber(tostring(msg.myScore));

    rankVersion = msg.rankVersion
    rankInfo.ranks = {};

    for i = 1, #msg.ranks do
        local rank = msg.ranks[i];
        local info = {};
        info["rank"] = i;
        info["playerId"] = rank.playerId;
        info["name"] = rank.name;
        info["headId"] = rank.headIcon;
        info["headFrame"] = rank.headFrame;
        info["score"] = tonumber(tostring(rank.score));
        info["level"] = rank.level;
        info["power"] = tonumber(tostring(rank.power));
        table.insert(rankInfo.ranks, info);
    end

    local rank = Util.GetPlayerPrefs(logicMgr.HeroManager.GetRoleInfo().playerId .. "_ArenaRank");
    if rank ~= nil then
        rank = tonumber(rank);
        if rank == -1 or rank > msg.myRank then
            Util.SetPlayerPrefs(logicMgr.HeroManager.GetRoleInfo().playerId .. "_ArenaRank", msg.myRank);
        end
    else
        Util.SetPlayerPrefs(logicMgr.HeroManager.GetRoleInfo().playerId .. "_ArenaRank", msg.myRank);
    end
end

--- 设置挑战列表信息
--- @param msg ResArenaOpponentMessage 竞技场匹配对战列表消息
function ArenaManager.setOpponentInfo(msg)
    baseInfo["rank"] = msg.rank;
    baseInfo["score"] = msg.score;
    opponentInfo = {};
    if msg.foeList ~= nil then
        local list = msg.foeList;
        for i = 1, #list do
            local info = {};
            info["isAI"] = list[i].isAi;
            info["leaderId"] = list[i].leaderId;
            info["power"] = list[i].maxPower;
            info["name"] = list[i].name;
            info["head"] = list[i].pic;
            info["playerId"] = list[i].playerId;
            info["score"] = list[i].score;
            info["formation"] = {};
            info["skillId"] = list[i].skillId;
            info["otherPetInfo"] = list[i].petInfo;
            for k = 1, #list[i].formations do
                local single = list[i].formations[k];
                info["formation"][k] = {
                    index = k,
                    skinId = single.useSkinId;
                    level = single.level,
                    partnerId = single.partnerId,
                    partnerModelId = single.partnerModelId,
                    star = single.star,
                    weaponLevel = single.weaponLevel,
                    weaponRank = single.weaponRank,
                    skinId = single.useSkinId
                };
            end
            table.insert(opponentInfo, info);
        end
        table.sort(opponentInfo, function(a, b)
            return a.score > b.score;
        end);
    end
end

function ArenaManager.refreshBattleInfo(msg)
    this.setLastBaseInfo(baseInfo);
    if msg["fightResult"] == 1 then
        baseInfo["winCount"] = baseInfo["winCount"] + 1;
    end
    this.resultDic.current_list = baseInfo["rank"];

    this.resultDic.delta_rank = msg["rank"] - baseInfo["rank"]
    this.resultDic.delta_score = msg["score"] - baseInfo["score"]
    this.resultDic.last_rank = baseInfo.rank
    this.resultDic.last_score = baseInfo["score"]

    baseInfo["times"] = baseInfo["times"] + 1;
    baseInfo["rank"] = msg["rank"];  --排行
    baseInfo["score"] = msg["score"];  --积分
    baseInfo["add"] = msg["add"];--增加的分数
    local addScore = msg["fightResult"] == 1 and baseInfo.add  or baseInfo.add * -1 ;
    local lastCfg, curLevel = logicMgr.ArenaManager.getLevelConfigByScore(baseInfo.score - addScore, EnumConst.ArenaBattleType.Normal)
    local gradingCfg, newLevel = logicMgr.ArenaManager.getLevelConfigByScore(baseInfo.score, EnumConst.ArenaBattleType.Normal)

    if tonumber(curLevel) < tonumber(newLevel) then
        baseInfo["isLevelUp"] = 1;
    else
        baseInfo["isLevelUp"] = 0;
    end
    this.resultDic.running_time = tonumber(msg.record.time)
    this.resultDic.battle_log_id = tostring(msg.record.fightId)
    this.resultDic.current_win_count = baseInfo["winCount"];
    this.resultDic.current_score = tonumber(msg["score"])
    this.resultDic.current_rank = tonumber(msg.rank)
    
end

--- 设置对战记录信息
--- @param serverRecordVer number 服务器上的记录版本号
--- @param records table<number, BattleRecord> 战斗记录列表
function ArenaManager.setRecordInfo(serverRecordVer, records)
    if serverRecordVer == recordVersion then
        return ;
    end

    recordVersion = serverRecordVer;
    recordInfo = records or {};

    table.sort(recordInfo, function(a, b)
        return a.createTime > b.createTime;
    end);
end

--- 设置分享战报列表
--- @param msg ResArenaSharedRecordsMessage 竞技场分享战报列表消息
function ArenaManager.setSharedRecords(msg)
    specialBattleInfo = msg.records or {};
    table.sort(specialBattleInfo, function(a, b)
        return a.createTime > b.createTime;
    end);
end

function ArenaManager.addRewardBox(boxId)
    table.insert(baseInfo["hasReward"], boxId);
end

function ArenaManager.addBuyTicketCount(count)
    baseInfo["buyCount"] = baseInfo["buyCount"] + count;
end

function ArenaManager.getBaseInfo()
    return baseInfo;
end

function ArenaManager.IsGetReward(boxId)
    for i = 1, #baseInfo.hasReward do
        if boxId == baseInfo.hasReward[i] then
            return true;
        end
    end
    return false;
end

function ArenaManager.getGradCofigByScore(score)
    return ArenaManager.getLevelConfigByScore(score, EnumConst.ArenaBattleType.Normal)
end

function ArenaManager.getRewardConfigByRank(rank)
    -- 获取排行奖励配置
    local singleRewardConfig = nil;
    local maxId = 0;
    for key, value in pairs(arenaRewardConfig) do
        if value.f_RankStart <= rank and value.f_RankEnd >= rank then
            singleRewardConfig = value;
            break ;
        end
        if value.f_Id > maxId then
            maxId = value.f_Id;
        end
    end
    if singleRewardConfig == nil then
        singleRewardConfig = arenaRewardConfig[tostring(maxId)];
    end
    return singleRewardConfig;
end

function ArenaManager.requestOpponentInfo(forcedToPull)
    --成功的回调函数，是否强制刷新
    if forcedToPull == true or opponentInfo == nil or #opponentInfo == 0 then
        arenaHandler.sendArenaOpponentMessage();
    end
end

function ArenaManager.getOpponentInfo()
    return opponentInfo or {};
end

function ArenaManager.getRankInfo()
    return clone(rankInfo) or {}
end

function ArenaManager.setLastBaseInfo(data)
    this.lastScore = {};
    this.lastScore["winCount"] = data["winCount"];
    this.lastScore["times"] = data["times"];
    this.lastScore["rank"] = data["rank"];
    this.lastScore["score"] = data["score"];
end

function ArenaManager.getLastBaseInfo()
    return this.lastScore or {}
end

function ArenaManager.getRecords()
    return clone(recordInfo) or {};
end

function ArenaManager.getSharedRecords()
    return clone(specialBattleInfo or {});
end
-- 发送竞技场记录请求
function ArenaManager.requestRecordInfo(forcedToPull)
    arenaHandler.sendArenaBattleRecords(recordVersion);
end

function ArenaManager.requestSharedRecords(forcedToPull)
    if forcedToPull == true or specialBattleInfo == nil or #specialBattleInfo == 0 then
        arenaHandler.sendArenaSharedRecords();
    end
end

function ArenaManager.requestRankInfo()
    arenaHandler.sendArenaGetRanks(recordVersion);
end

--- 添加精彩战斗
--- @param recordId string 战斗id
function ArenaManager.sendAddSpecialBattle(recordId)
    local request = ReqArenaAddSharedRecordMessage.New();
    request.fightId = recordId;
    sendReqMessage(request);
end

function ArenaManager.getOppoMonster(playerId)
    local oppoInfo = nil;
    for i = 1, #opponentInfo do
        if opponentInfo[i]["playerId"] == playerId then
            oppoInfo = opponentInfo[i];
            break ;
        end
    end
    if oppoInfo ~= nil then
        local monster = {};
        for i = 1, #oppoInfo.formation do
            --printTable(oppoInfo.formation[i]);
            table.insert(monster, oppoInfo.formation[i]);
        end
        return monster;
    end
    return nil;
end

function ArenaManager.geRecordMonster(playerId)
    local oppoInfo = nil;
    for i = 1, #recordInfo do
        if recordInfo[i]["attacker"]["playerId"] == playerId or recordInfo[i]["defender"]["playerId"] == playerId then
            oppoInfo = recordInfo[i];
            break ;
        end
    end
    if oppoInfo ~= nil then
        if oppoInfo["defender"]["playerId"] == playerId then
            return oppoInfo["defender"];

        elseif oppoInfo["attacker"]["playerId"] == playerId then
            return oppoInfo["attacker"];

        end


    end
    return nil;
end

--- 战报分享成功事件
--- @param fightId string 战报id
function ArenaManager.onAddSharedSuccess(fightId)
    UISysTips.AddMsg("分享成功");
end

function ArenaManager.getLevelConfigByScore(score, _arena_type)
    local gradingCfg = nil
    _arena_type = _arena_type or EnumConst.ArenaBattleType.Normal
    if _arena_type == EnumConst.ArenaBattleType.Normal then
        gradingCfg = G.dataTable["t_athleticsgrading"]
    elseif _arena_type == EnumConst.ArenaBattleType.Cross then
        gradingCfg = G.dataTable["t_athleticsgradingcs"]
    elseif _arena_type == EnumConst.ArenaBattleType.TeamCross then
        return
    else 
        error("竞技场玩法类型错误") 
    end
    local cur_cfg = {} 
    for _, v in pairs(gradingCfg) do
        table.insert(cur_cfg, v)
    end
    table.sort(cur_cfg, function( a, b )
        return tonumber(a.f_Integral) < tonumber(b.f_Integral)
    end)
    local cur_score = tonumber(score)
    for k, v in ipairs(cur_cfg) do
        if cur_cfg[k+1] == nil or cur_score < tonumber(cur_cfg[k+1].f_Integral) then
            return v, tostring(v.f_Id)
        end
    end
end


------------------------------------------------------------
-- 竞技场跨服逻辑
------------------------------------------------------------
this.cross_base_info = {} -- 跨服竞技场基础信息
-- 初始化数据
function ArenaManager.initCrossBaseInfo()
    this.cross_base_info["freeTimes"]     = HelperFunc.GetGlobalNumVlue(377)  -- 每日免费挑战次数
    this.cross_base_info["times"]         = 0                                 -- 今日已挑战次数
    this.cross_base_info["buyCount"]      = 0                                 -- 今日已购买次数
    this.cross_base_info["endTime"]       = 0                                 -- 本赛季结束时间
    this.cross_base_info["rank"]          = 0                                 -- 排行
    this.cross_base_info["score"]         = 0                                 -- 积分
    this.cross_base_info["isLevelUp"]     = 0 
    this.cross_base_info["seasonEndTime"] = 0                                 --赛季结束时间(下一次开启) 

end
-- 同步跨服竞技场信息
function ArenaManager.setCrossBaseInfo(msg)
    this.cross_base_info["endTime"]       = tonumber(tostring(msg["endTime"]))             -- 本赛季结束时间
    this.cross_base_info["seasonEndTime"] = tonumber(tostring(msg["seasonEndTime"]))       --赛季结束时间(下一次开启) 
    this.cross_base_info["winCount"]      = msg["winCount"]
    this.cross_base_info["hasReward"]     = msg["drawBox"]                                 -- 已领取的奖励宝箱
    this.cross_base_info["times"]         = msg["battleCount"]
    this.cross_base_info["buyCount"]      = msg["buyCount"]
    this.cross_base_info["rank"]          = msg["myRank"]                                  --排行
    this.cross_base_info["score"]         = tostring(msg["myScore"])                       --积分
    this.cross_base_info["power"]         = msg["myDefPower"]
    this.cross_base_info["isLevelUp"]     = 0

    FormationManager.SetFormation(EnumConst.FormationType.CrossArenaAtk, msg["ackFormation"])
    FormationManager.SetFormation(EnumConst.FormationType.CrossArenaDef, msg["defFormation"])
end
-- 返回跨服基础信息数据
function ArenaManager.getCrossBaseInfo()
    return this.cross_base_info
end

-- 请求跨服对手数据
function ArenaManager.requestCrossOpponentInfo(forcedToPull)
    --成功的回调函数，是否强制刷新
    if forcedToPull == true or this.cross_opponentInfo == nil or #this.cross_opponentInfo == 0 then
       crossArenaHandler.sendCrossArenaOpponentMessage()
    end
end
-- 根据玩家id获取跨服敌方阵容
function ArenaManager.getCrossOppoMonster(playerId)
    local oppoInfo = nil;
    for i = 1, #this.cross_opponentInfo do
        if this.cross_opponentInfo[i]["playerId"] == playerId then
            oppoInfo = this.cross_opponentInfo[i]
            break
        end
    end
    if oppoInfo ~= nil then
        local monster = {};
        for i = 1, #oppoInfo.formation do
            table.insert(monster, oppoInfo.formation[i])
        end
        return monster
    end
    return nil
end
--- 设置跨服挑战列表信息  竞技场匹配对战列表消息
function ArenaManager.setCrossOpponentInfo(msg)
    -- print("--------------------------------->", table.tostring(msg) )
    this.cross_base_info["rank"] = msg.rank;
    this.cross_base_info["score"] = msg.score;
    this.cross_opponentInfo = {}
    if msg.foeList ~= nil then
        local list = msg.foeList
        for i = 1, #list do
            local info = {};
            info["isAI"] = list[i].isAi
            info["leaderId"] = list[i].leaderId
            info["power"] = list[i].maxPower
            info["name"] = list[i].name
            info["head"] = list[i].pic
            info["playerId"] = list[i].playerId
            info["score"] = list[i].score
            info["formation"] = {}
            info["skillId"] = list[i].skillId;
            info["server_id"] = list[i].serverId or 0
            info["otherPetInfo"] = list[i].petInfo
            for k = 1, #list[i].formations do
                local single = list[i].formations[k]
                info["formation"][k] = {
                    index = k,
                    level = single.level,
                    partnerId = single.partnerId,
                    partnerModelId = single.partnerModelId,
                    star = single.star,
                    weaponLevel = single.weaponLevel,
                    weaponRank = single.weaponRank
                };
            end
            table.insert(this.cross_opponentInfo, info)
        end
        table.sort(this.cross_opponentInfo, function(a, b)
            return a.power > b.power
        end);
    end
end
function ArenaManager.getCrossOpponentInfo()
    return this.cross_opponentInfo or {}
end

function ArenaManager.setLastCrossBaseInfo(data)
    this.lastCrossScore = {}
    this.lastCrossScore["winCount"] = data["winCount"]
    this.lastCrossScore["times"] = data["times"]
    this.lastCrossScore["rank"] = data["rank"]
    this.lastCrossScore["score"] = data["score"]
end
function ArenaManager.getLastCrossBaseInfo()
    return this.lastCrossScore or {}
end

this.resultDicCross = {}    --跨服埋点信息
-- 刷新跨服战斗信息
function ArenaManager.refreshCrossBattleInfo(msg)
    this.setLastCrossBaseInfo(this.cross_base_info)
    if msg["fightResult"] == 1 then
        this.cross_base_info["winCount"] = this.cross_base_info["winCount"] + 1;
    end
    this.resultDicCross.current_list = this.cross_base_info["rank"]; 
    this.resultDicCross.delta_rank = msg["rank"] - this.cross_base_info["rank"]
    this.resultDicCross.delta_score = msg["score"] - this.cross_base_info["score"]
    this.resultDicCross.last_rank = this.cross_base_info.rank
    this.resultDicCross.last_score = this.cross_base_info["score"]

    this.cross_base_info["times"] = this.cross_base_info["times"] + 1
    this.cross_base_info["rank"] = msg["rank"]  --排行
    this.cross_base_info["score"] = msg["score"]  --积分
    this.cross_base_info["add"] = msg["add"]--增加的分数
    local lastCfg, curLevel = logicMgr.ArenaManager.getLevelConfigByScore(this.cross_base_info.score - this.cross_base_info.add, EnumConst.ArenaBattleType.Cross)
    local gradingCfg, newLevel = logicMgr.ArenaManager.getLevelConfigByScore(this.cross_base_info.score, EnumConst.ArenaBattleType.Cross);

    if tonumber(curLevel) < tonumber(newLevel) then
        this.cross_base_info["isLevelUp"] = 1;
    else
        this.cross_base_info["isLevelUp"] = 0;
    end
    this.resultDicCross.running_time = tonumber(msg.record.time)
    this.resultDicCross.battle_log_id = tostring(msg.record.fightId)
    this.resultDicCross.current_win_count = this.cross_base_info["winCount"];
    this.resultDicCross.current_score = tonumber(msg["score"])
    this.resultDicCross.current_rank = tonumber(msg.rank)
    
end
-- 添加跨服挑战券购买数量
function ArenaManager.addBuyCrossTicketCount(count)
    this.cross_base_info["buyCount"] = this.cross_base_info["buyCount"] + count
end

-- 设置领取的跨服宝箱
function ArenaManager.addCrossRewardBox(boxId)
    table.insert(this.cross_base_info["hasReward"], boxId)
end

local crossRankVerion = -1
local crossRankInfo = {} -- 跨服排行信息
-- 更新跨服排行数据
function ArenaManager.setCrossRankInfo(msg)
    -- print("ArenaManager.setCrossRankInfo->", table.tostring(msg) )
    crossRankInfo.myRank = crossRankInfo.myRank or {};
    local roleInfo = logicMgr.HeroManager.GetRoleInfo()
    crossRankInfo.myRank["playerId"] = roleInfo.playerId;
    crossRankInfo.myRank["name"] = roleInfo.name;
    crossRankInfo.myRank["headId"] = roleInfo.pic;
    crossRankInfo.myRank["level"] = roleInfo.level;
    crossRankInfo.myRank["power"] = roleInfo.maxPower;
    crossRankInfo.myRank["headFrame"] = roleInfo.picFrame;
    if crossRankVerion == msg.rankVersion then
        return
    end
    crossRankInfo.myRank["rank"] = msg.myRank;
    crossRankInfo.myRank["score"] = tonumber(tostring(msg.myScore));

    crossRankVerion = msg.rankVersion
    crossRankInfo.ranks = {};

    for i = 1, #msg.ranks do
        local rank = msg.ranks[i];
        local info = {};
        info["rank"] = i;
        info["playerId"] = rank.playerId;
        info["name"] = rank.name;
        info["headId"] = rank.headIcon;
        info["headFrame"] = rank.headFrame;
        info["score"] = tonumber(tostring(rank.score));
        info["level"] = rank.level;
        info["power"] = tonumber(tostring(rank.power));
        info["serverId"] = rank.serverId
        table.insert(crossRankInfo.ranks, info);
    end


    local rank = Util.GetPlayerPrefs(logicMgr.HeroManager.GetRoleInfo().playerId .. "_CrossArenaRank");
    if rank ~= nil then
        rank = tonumber(rank);
        if rank == -1 or rank > msg.myRank then
            Util.SetPlayerPrefs(logicMgr.HeroManager.GetRoleInfo().playerId .. "_CrossArenaRank", msg.myRank);
        end
    else
        Util.SetPlayerPrefs(logicMgr.HeroManager.GetRoleInfo().playerId .. "_CrossArenaRank", msg.myRank);
    end
end
-- 返回跨服排行信息
function ArenaManager.getCrossRankInfo()
    -- print("ArenaManager.getCrossRankInfo->", table.tostring(crossRankInfo) )
    return clone(crossRankInfo) or {}
end

local crossRecordVersion = -1
local crossRecordInfo = {}
function ArenaManager.getCrossRecords()
    return clone(crossRecordInfo) or {}
end
-- 发送跨服竞技场记录请求
function ArenaManager.requestCrossRecordInfo(forcedToPull)
    crossArenaHandler.sendCrossArenaBattleRecords(crossRecordVersion)
end
--- 设置对战记录信息
--- @param serverRecordVer number 服务器上的记录版本号
--- @param records table<number, BattleRecord> 战斗记录列表
function ArenaManager.setCrossRecordInfo(serverRecordVer, records)
    if serverRecordVer == crossRecordVersion then
        return
    end

    crossRecordVersion = serverRecordVer
    crossRecordInfo = records or {}

    table.sort(crossRecordInfo, function(a, b)
        return a.createTime > b.createTime;
    end);
end
function ArenaManager.getCrossRecordMonster(playerId)
    local oppoInfo = nil;
    for i = 1, #crossRecordInfo do
        if crossRecordInfo[i]["attacker"]["playerId"] == playerId or crossRecordInfo[i]["defender"]["playerId"] == playerId then
            oppoInfo = crossRecordInfo[i];
            break ;
        end
    end
    if oppoInfo ~= nil then
        if oppoInfo["defender"]["playerId"] == playerId then
            return oppoInfo["defender"];

        elseif oppoInfo["attacker"]["playerId"] == playerId then
            return oppoInfo["attacker"];

        end 
    end
    return nil;
end
-- 请求跨服排行请求
function ArenaManager.requestCrossRankInfo()
    -- print("ArenaManager.requestCrossRankInfo--->", crossRankVerion)
    crossArenaHandler.sendCrossArenaGetRanks(crossRankVerion)
end

--- 添加跨服精彩战斗
--- @param recordId string 战斗id
function ArenaManager.sendCrossAddSpecialBattle(recordId)
    crossArenaHandler.sendCrossAddSpecialBattle(recordId)
end
 
 ---跨服战报分享成功事件
--- @param fightId string 战报id
function ArenaManager.onAddCrossSharedSuccess(fightId)
    UISysTips.AddMsg("分享成功");
end

local specialCrossBattleInfo = {}
--- 设置分享跨服战报列表
--- @param msg ResArenaSharedRecordsMessage 竞技场分享战报列表消息
function ArenaManager.setCrossSharedRecords(msg)
    specialCrossBattleInfo = msg.records or {};
    table.sort(specialCrossBattleInfo, function(a, b)
        return a.createTime > b.createTime;
    end);
end
-- 请求跨服分享记录
function ArenaManager.requestCrossSharedRecords(forcedToPull)
    if forcedToPull == true or specialCrossBattleInfo == nil or #specialCrossBattleInfo == 0 then
        crossArenaHandler.sendCrossArenaSharedRecords()
    end
end
function ArenaManager.getCrossSharedRecords()
    return clone(specialCrossBattleInfo or {})
end
------------------------------------------------------------
-- end
------------------------------------------------------------





------------------------------------------------------------
-- 竞技场跨服组队逻辑
------------------------------------------------------------
this.cross_team_base_info = {} -- 跨服组队竞技场基础信息
-- 初始化跨服组队数据
function ArenaManager.initCrossTeamBaseInfo()
    this.cross_team_base_info["freeTimes"]     = HelperFunc.GetGlobalNumVlue(416)  -- 每日免费挑战次数
    this.cross_team_base_info["times"]         = 0                                 -- 今日已挑战次数
    this.cross_team_base_info["buyCount"]      = 0                                 -- 今日已购买次数
    this.cross_team_base_info["endTime"]       = 0                                 -- 本赛季结束时间
    this.cross_team_base_info["rank"]          = 0                                 -- 排行
    this.cross_team_base_info["score"]         = 0                                 -- 积分
    this.cross_team_base_info["isLevelUp"]     = 0 
    this.cross_team_base_info["seasonEndTime"] = 0                                 --赛季结束时间(下一次开启) 
    this.cross_team_base_info["award"]         = 0
end

function ArenaManager.setCrossTeamAward( award )
    local add_award = award and tonumber(tostring(award)) or 0
    local cur_award = this.cross_team_base_info["award"] or 0
    if cur_award-add_award >= 0 then
        this.cross_team_base_info["award"] = cur_award-add_award
    else
        this.cross_team_base_info["award"] = 0
    end
    local rewards = {}
    local item = {}
    item.num = add_award
    item.itemModelId = 31
    table.insert(rewards, item)
    showUI(PanelNames.UICommonItemGet, nil, nil, 3, rewards) 
    FireEvent(Config.EventType.Fresh_CrossTeamArenaAward)
end

-- 同步跨服组队竞技场信息
function ArenaManager.setCrossTeamBaseInfo(msg)
    this.cross_team_base_info["endTime"]       = tonumber(tostring(msg["endTime"]))        -- 本赛季结束时间
    this.cross_team_base_info["seasonEndTime"] = tonumber(tostring(msg["seasonEndTime"]))  -- 赛季结束时间(下一次开启) 
    this.cross_team_base_info["winCount"]      = msg["winCount"]                           -- 本周胜利次数
    this.cross_team_base_info["hasReward"]     = msg["drawBox"]                            -- 已领取宝箱Id list
    this.cross_team_base_info["times"]         = msg["battleCount"]                        -- 挑战次数
    this.cross_team_base_info["buyCount"]      = msg["buyCount"]                           -- 购买次数
    this.cross_team_base_info["rank"]          = msg["myRank"]                             -- 我的高阶竞技场排名
    this.cross_team_base_info["power"]         = msg["myDefPower"]                         -- 我的防守战力

    -- this.cross_team_base_info["isLevelUp"]     = 0
    this.cross_team_base_info["award"]         = msg["award"] and tonumber(tostring(msg["award"]) )  or 0 -- 可领取的代币数
   
    this.cross_team_base_info["duanwei_award"] = {}
    if msg.danAwards ~= nil then
        for _, v in pairs(msg.danAwards) do
            this.cross_team_base_info["duanwei_award"][v.danId] = v.status
        end
    end

    local new_score = tonumber(tostring(msg["myScore"]))     --排行
    local old_score = this.cross_team_base_info["score"]
    this.cross_team_base_info["score"]         = tonumber(tostring(msg["myScore"]))                  -- 我的高阶竞技场积分
    if old_score ~= 0 and this.cross_team_base_info["isLevelUp"] ~= 1 then
        local cfg_matching1 = logicMgr.ArenaManager.getArenaMatchingConfigByRank( old_score )
        local cfg_matching2 = logicMgr.ArenaManager.getArenaMatchingConfigByRank( new_score )
        local curLevel = cfg_matching1 and cfg_matching1.f_RankId or 0
        local newLevel = cfg_matching2 and cfg_matching2.f_RankId or 0 
        if tonumber(curLevel) < tonumber(newLevel) then
            this.cross_team_base_info["isLevelUp"] = 1
        else
            this.cross_team_base_info["isLevelUp"] = 0
        end
    end
 
    local my_ack_formations = {}
    local ackFormation = msg["ackFormation"]
    if ackFormation ~= nil and next(ackFormation) ~= nil then
        for k, v in ipairs(ackFormation) do
            my_ack_formations[k] = v.formation
        end
    else
        for i=1, 3 do
            my_ack_formations[i] = {}
        end
    end
    logicMgr.FormationManager.SetFormation(EnumConst.FormationType.TeamCrossArenaAtk, my_ack_formations)
    local my_def_formations = {}
    local defFormation = msg["defFormation"]
    if defFormation ~= nil and next(defFormation) ~= nil then
        for k, v in ipairs(defFormation) do
            my_def_formations[k] = v.formation
        end
    else
        for i=1, 3 do
            my_def_formations[i] = {}
        end
    end
    FormationManager.SetFormation(EnumConst.FormationType.TeamCrossArenaDef, my_def_formations)
end

function ArenaManager.GetDuanWeiStatusByDuanWeiId( _id )
    if _id ~= nil then
        local status = this.cross_team_base_info["duanwei_award"][tonumber(_id)]
        if status ~= nil then
            return status
        end
    end

    return 0
end

function ArenaManager.GetCrossTeamNewDuanWeiAward()
    return this.cross_team_base_info["duanwei_award"] or {}
end
function ArenaManager.refreshCrossTeamNewDuanWeiAward( list , status )
    if this.cross_team_base_info["duanwei_award"] == nil then
        this.cross_team_base_info["duanwei_award"] = {}
    end
    if list ~= nil then
        for _, v in pairs( list ) do
            this.cross_team_base_info["duanwei_award"][tonumber(v)] = status
        end
    end
    FireEvent(Config.EventType.Fresh_CrossTeamRewardPreview)
end

-- 返回跨服组队基础信息数据
function ArenaManager.getCrossTeamBaseInfo()
    return this.cross_team_base_info
end

-- 获取高阶竞技场可领取代币数量
function ArenaManager.getCrossTeamAward()
    if this.cross_team_base_info ~= nil then
        return this.cross_team_base_info["award"];
    end
    return 0;
end

function ArenaManager.TempCrossTeamAwardCount()
    if this.cross_team_base_info ~= nil then
        local rank = this.cross_team_base_info.rank;
        if this.cross_team_base_info.rank < 131 then
            local gradingCfg, cfg_arena_matching_item = ArenaManager.getAthleticGradingConfigByRank(rank)
            this.cross_team_base_info["award"] = this.cross_team_base_info["award"] + tonumber(cfg_arena_matching_item.f_Coin);

            if isOpenUI(PanelNames.UIAdventureMain) then
                local ui_adventure_main = CtrlManager.GetCtrl(PanelNames.UIAdventureMain)
                ui_adventure_main.RefreshArenaAward()
            end
        end
    end
end

-- 高阶竞技场代币是否可快速领取
function ArenaManager.isGetCrossTeamAward()
    if this.cross_team_base_info ~= nil then
        local gradingCfg, cfg_arena_matching_item = ArenaManager.getAthleticGradingConfigByRank(this.cross_team_base_info.rank)
        local rate = this.cross_team_base_info.award / cfg_arena_matching_item.f_CoinLimit
        if rate >= 0.5 then
            return true;
        end
    end
    return false;
end

--设置上一次信息
function ArenaManager.setLastCrossTeamBaseInfo(data)
    this.lastCrossTeamScore = {}
    this.lastCrossTeamScore["winCount"] = data["winCount"]
    this.lastCrossTeamScore["times"] = data["times"]
    this.lastCrossTeamScore["rank"] = data["rank"]
    this.lastCrossTeamScore["score"] = data["score"]
end
-- 返回上一次信息
function ArenaManager.getLastCrossTeamBaseInfo()
    return this.lastCrossTeamScore or {}
end

--跨服组队埋点信息
this.resultDicCrossTeam = {}    
-- 刷新跨服组队战斗信息
function ArenaManager.refreshCrossTeamBattleInfo(msg)
    this.setLastCrossTeamBaseInfo(this.cross_team_base_info)
    if msg["fightResult"] == 1 then
        this.cross_team_base_info["winCount"] = this.cross_team_base_info["winCount"] + 1;
    end
    this.resultDicCrossTeam.current_list = this.cross_team_base_info["rank"]
    this.resultDicCrossTeam.delta_rank = msg["rank"] - this.cross_team_base_info["rank"]
    this.resultDicCrossTeam.delta_score = msg["score"] - this.cross_team_base_info["score"]
    this.resultDicCrossTeam.last_rank = this.cross_team_base_info.rank
    this.resultDicCrossTeam.last_score = this.cross_team_base_info["score"]

    local new_score = tonumber(tostring(msg["score"])) or 0     --排行
    local old_score = tonumber(tostring(this.cross_team_base_info["score"])) or 0
    this.cross_team_base_info["times"] = this.cross_team_base_info["times"] + 1
    this.cross_team_base_info["rank"] = new_score
    this.cross_team_base_info["score"] = msg["score"]   --积分
    this.cross_team_base_info["add"] = msg["add"]       --增加的分数

    local cfg_matching1 = logicMgr.ArenaManager.getArenaMatchingConfigByRank( old_score )
    local cfg_matching2 = logicMgr.ArenaManager.getArenaMatchingConfigByRank( new_score )
    local curLevel = cfg_matching1 and cfg_matching1.f_RankId or 0
    local newLevel = cfg_matching2 and cfg_matching2.f_RankId or 0

    if this.cross_team_base_info["isLevelUp"] ~= 1 then
        if tonumber(curLevel) < tonumber(newLevel) then
            this.cross_team_base_info["isLevelUp"] = 1
        else
            this.cross_team_base_info["isLevelUp"] = 0
        end
    end
    this.resultDicCrossTeam.running_time = tonumber(tostring(msg.record.time))
    this.resultDicCrossTeam.battle_log_id = tostring(msg.record.fightId)
    this.resultDicCrossTeam.current_win_count = this.cross_team_base_info["winCount"]
    this.resultDicCrossTeam.current_score = tonumber(tostring(msg["score"]))
    this.resultDicCrossTeam.current_rank = tonumber(tostring(msg.rank))
end

-- 设置领取的跨服组队宝箱
function ArenaManager.addCrossTeamRewardBox(boxId)
    table.insert(this.cross_team_base_info["hasReward"], boxId)
end
-- 添加跨服组队竞技场挑战券购买数量
function ArenaManager.addBuyCrossTeamTicketCount(count)
    this.cross_team_base_info["buyCount"] = this.cross_team_base_info["buyCount"] + count
end

--- 设置跨服组队挑战列表信息  竞技场匹配对战列表消息
function ArenaManager.setCrossTeamOpponentInfo(msg)
    this.cross_team_base_info["rank"] = msg.rank
    this.cross_team_base_info["score"] = msg.score
    this.cross_team_opponentInfo = {}
    if msg.foeList ~= nil then
        local list = msg.foeList
        for i = 1, #list do
            local info = {};
            info["isAI"] = list[i].isAi
            info["leaderId"] = list[i].leaderId
            info["power"] = list[i].maxPower
            info["name"] = list[i].name
            info["head"] = list[i].pic
            info["playerId"] = list[i].playerId
            info["score"] = list[i].score
            info["formation"] = {}
            info["server_id"] = list[i].serverId or 0
            info["otherPetInfo"] = list[i].petInfo
            info["skillId"] = list[i].skillId
            info["formations"] = {}
            info["teamPower"] = {}
            for k = 1, #list[i].formations do
                local cur_formation = list[i].formations[k]
                local formation = {}
                for k1=1, #cur_formation.formations do
                    local single = cur_formation.formations[k1]
                    formation[k1] = {
                        index = k1,
                        level = single.level,
                        partnerId = single.partnerId,
                        partnerModelId = single.partnerModelId,
                        star = single.star,
                        weaponLevel = single.weaponLevel,
                        weaponRank = single.weaponRank
                    };
                end
                table.insert(info["formations"], formation)
                table.insert(info["teamPower"], tonumber(tostring(cur_formation.teamPower)))
            end
            table.insert(this.cross_team_opponentInfo, info)
        end
        table.sort(this.cross_team_opponentInfo, function(a, b)
            return a.power > b.power
        end);
    end
end
function ArenaManager.getCrossTeamOpponentInfo()
    return this.cross_team_opponentInfo or {}
end

local crossTeamRecordVersion = -1
local crossTeamRecordInfo = {}
function ArenaManager.getCrossTeamRecords()
    return clone(crossTeamRecordInfo) or {}
end
-- 发送跨服组队竞技场记录请求
function ArenaManager.requestCrossTeamRecordInfo(forcedToPull)
    crossTeamArenaHandler.sendReqHighArenaBattleRecords(crossTeamRecordVersion)
end
--- 设置对战记录信息
--- @param serverRecordVer number 服务器上的记录版本号
--- @param records table<number, BattleRecord> 战斗记录列表
function ArenaManager.setCrossTeamRecordInfo(serverRecordVer, records)
    if serverRecordVer == crossTeamRecordVersion then
        return
    end 
    crossTeamRecordVersion = serverRecordVer
    crossTeamRecordInfo = records or {}
    table.sort(crossTeamRecordInfo, function(a, b)
        return a.records[1].createTime > b.records[1].createTime
    end);
end

function ArenaManager.getCrossTeamRecordMonster( playerId )
    local oppoInfo = nil
    for i = 1, #crossTeamRecordInfo do
        if crossTeamRecordInfo[i]["atkId"] == playerId or crossTeamRecordInfo[i]["defId"] == playerId then
            oppoInfo = crossTeamRecordInfo[i]
            break
        end
    end
    if oppoInfo ~= nil then
        if oppoInfo["defId"] == playerId then
            local defender = {}
            for k=1, #oppoInfo["records"] do
                table.insert(defender, oppoInfo[k]["defender"])
            end
            return defender

        elseif oppoInfo["atkId"] == playerId then
            local attacker = {}
            for k=1, #oppoInfo["records"] do
                table.insert(attacker, oppoInfo[k]["attacker"])
            end
            return attacker
        end 
    end
    return nil
end

--- @param fightId string 战报id
function ArenaManager.onAddCrossTeamSharedSuccess(fightId)
    UISysTips.AddMsg("分享成功");
end

local specialCrossTeamBattleInfo = {}
--- 设置分享跨服战报列表
--- @param msg ResArenaSharedRecordsMessage 竞技场分享战报列表消息
function ArenaManager.setCrossTeamSharedRecords(msg)
    specialCrossTeamBattleInfo = msg.records or {}
    table.sort(specialCrossTeamBattleInfo, function(a, b)
        return a.createTime > b.createTime
    end);
end

local crossTeamRankVerion = -1
local crossTeamRankInfo = {} -- 跨服组队排行信息
-- 更新跨服排行数据
function ArenaManager.setCrossTeamRankInfo(msg)
    crossTeamRankInfo.myRank = crossTeamRankInfo.myRank or {}
    local roleInfo = logicMgr.HeroManager.GetRoleInfo()  
    crossTeamRankInfo.myRank["playerId"] = roleInfo.playerId
    crossTeamRankInfo.myRank["name"] = roleInfo.name
    crossTeamRankInfo.myRank["headId"] = roleInfo.pic
    crossTeamRankInfo.myRank["level"] = roleInfo.level
    crossTeamRankInfo.myRank["power"] = roleInfo.maxPower
    crossTeamRankInfo.myRank["headFrame"] = roleInfo.picFrame
    crossTeamRankInfo.myRank["serverId"] = AppConst.ServerId 
    if crossTeamRankVerion == msg.rankVersion then return end 
    crossTeamRankInfo.myRank["rank"] = msg.myRank 
    crossTeamRankInfo.myRank["score"] = tonumber(tostring(msg.myScore)) 
    crossTeamRankVerion = msg.rankVersion
    crossTeamRankInfo.ranks = {}

    for i = 1, #msg.ranks do
        local rank = msg.ranks[i];
        local info = {};
        info["rank"] = i;
        info["playerId"] = rank.playerId;
        info["name"] = rank.name;
        info["headId"] = rank.headIcon;
        info["headFrame"] = rank.headFrame;
        info["score"] = tonumber(tostring(rank.score));
        info["level"] = rank.level;
        info["power"] = tonumber(tostring(rank.power));
        info["serverId"] = rank.serverId
        table.insert(crossTeamRankInfo.ranks, info);
    end


    local rank = Util.GetPlayerPrefs(logicMgr.HeroManager.GetRoleInfo().playerId .. "_CrossTeamArenaRank")
    local my_new_rank = tonumber(tostring(msg.myRank) )
    if rank ~= nil then
        rank = tonumber(tostring(rank))
        if rank == -1 or my_new_rank > rank then
            Util.SetPlayerPrefs(logicMgr.HeroManager.GetRoleInfo().playerId .. "_CrossTeamArenaRank", my_new_rank);
        end
    else
        Util.SetPlayerPrefs(logicMgr.HeroManager.GetRoleInfo().playerId .. "_CrossArenaRank", my_new_rank);
    end

end
-- 返回跨服组队排行信息
function ArenaManager.getCrossTeamRankInfo()
    return clone(crossTeamRankInfo) or {}
end

-- 请求跨服组队分享记录
function ArenaManager.requestCrossTeamSharedRecords(forcedToPull)
    if forcedToPull == true or specialCrossTeamBattleInfo == nil or #specialCrossTeamBattleInfo == 0 then
       crossTeamArenaHandler.sendReqHighArenaSharedRecords()
    end
end

-- 请求跨服组队排行请求
function ArenaManager.requestCrossTeamRankInfo()  
    crossTeamArenaHandler.sendReqHighArenaGetRanks( crossTeamRankVerion )
end
 
 -- 请求跨服组队对手数据
function ArenaManager.requestCrossTeamOpponentInfo(forcedToPull)
    --成功的回调函数，是否强制刷新
    if forcedToPull == true or this.cross_team_opponentInfo == nil or #this.cross_team_opponentInfo == 0 then
       crossTeamArenaHandler.sendReqHighArenaOpponentMessage()
    end
end

--- 添加跨服精彩战斗
--- @param recordId string 战斗id
function ArenaManager.sendCrossTeamAddSpecialBattle(recordId)
    crossTeamArenaHandler.sendReqHighArenaAddSharedRecord( recordId )
end

function ArenaManager.getCrossTeamSharedRecords()
    return clone(specialCrossTeamBattleInfo or {})
end

-- 根据玩家id获取跨服組隊敌方阵容
function ArenaManager.getCrossTeamOppoMonster(playerId)
    local oppoInfo = nil
    if this.cross_team_opponentInfo ~= nil then
        for i = 1, #this.cross_team_opponentInfo do
            if this.cross_team_opponentInfo[i]["playerId"] == playerId then
                oppoInfo = this.cross_team_opponentInfo[i]
                break
            end
        end
        if oppoInfo ~= nil then
            local monster = {}
            for k1 = 1, #oppoInfo.formations do
                local formation = oppoInfo.formations[k1]
                monster[k1] = {}
                for k2 = 1, #formation do
                    table.insert(monster[k1], formation[k2])
                end
            end
            return monster, oppoInfo.teamPower;
        end
    end
    return nil, nil
end

function ArenaManager.getArenaMatchingConfigByRank( cur_rank )
    local arenamatchingCfg = G.dataTable["t_arenamatchinghl"]
    if cur_rank <= 0 or cur_rank >= 130 then cur_rank = 130 end
    local cfg_item = arenamatchingCfg[ tostring(cur_rank) ]
    if cfg_item ~= nil then
        return cfg_item
    end 
end

function ArenaManager.getAthleticGradingConfigByGradeId( grade_id )
 
    local athleticsgradingCfg = G.dataTable["t_athleticsgradinghl"]
    local cfg_item = athleticsgradingCfg[tostring(grade_id)]
    if cfg_item == nil then
        error("@策划 配置错误t_athleticsgradinghl 不存在grade_id"..tostring(grade_id))
    end
    return cfg_item 
end

function ArenaManager.getAthleticGradingConfigByRank( cur_rank )
    local arenamatchingCfg = G.dataTable["t_arenamatchinghl"]
    if cur_rank == nil or (cur_rank <= 0 or cur_rank >= 130) then cur_rank = 130 end
    local cfg_item = arenamatchingCfg[ tostring(cur_rank) ]
    if cfg_item ~= nil then
        local athleticsgradingCfg = G.dataTable["t_athleticsgradinghl"]
        local cfg_item1 = athleticsgradingCfg[tostring(cfg_item.f_RankId)]
        if cfg_item1 == nil then
            error("@策划 配置错误t_athleticsgradinghl 不存在f_RankId"..tostring(cfg_item.f_RankId))
        end
        return cfg_item1, cfg_item
    end 
end

-- 获取跨服多队新赛季红点状态
function ArenaManager.getCrossTeamOpenStatus()
    local seasonEndTime = Util.GetPlayerPrefs("crossTeamArenaBattle" .. logicMgr.HeroManager.GetRoleInfo().playerId);
    if seasonEndTime == nil then
        return true;
    end
    seasonEndTime = tonumber(seasonEndTime);
    if HelperFunc.GetServerTime(false) > seasonEndTime then
        return true;
    end
    return false;
end

-- 更新跨服多队新赛季红点状态
function ArenaManager.updateCrossTeamOpenStatus()
    local key = "crossTeamArenaBattle" .. logicMgr.HeroManager.GetRoleInfo().playerId;
    Util.SetPlayerPrefs(key, tostring(this.cross_team_base_info["seasonEndTime"]));
    if Util.GetPlayerPrefs("RedDotsCrossTeamArenaBattle"..logicMgr.HeroManager.GetRoleInfo().playerId) == nil then
        Util.SetPlayerPrefs("RedDotsCrossTeamArenaBattle"..logicMgr.HeroManager.GetRoleInfo().playerId, "1");
    end
    FireEvent(Config.EventType.Fresh_CrossTeamArenaRed);
end

function ArenaManager.setSomeBattleSkip(is)
    someBattleSkip = is;
end

function ArenaManager.getSomeBattleSkip()
    return someBattleSkip;
end

------------------------------------------------------------
-- end
------------------------------------------------------------
return ArenaManager